package com.meirengu.channel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.NiWoDaiService;
import com.meirengu.common.RedisClient;
import com.meirengu.utils.HttpUtil;
import com.meirengu.utils.StringUtil;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwThirdback;
import com.meirengu.webview.service.KwThirdbackService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 你我贷接口
 *
 * @author Mao
 * @create 2017-12-15 12:11
 */
@Service
public class NiWoDaiServiceImpl implements NiWoDaiService {

    Logger logger = LoggerFactory.getLogger(NiWoDaiServiceImpl.class);

    @Autowired
    RedisClient redisClient;

    @Autowired
    KwThirdbackService kwThirdbackService;

    /**
     * 商户身份验证接口
     *
     * @return
     */
    @Override
    public String merchValidate() {

        /*String token = redisClient.get("nwd_token");

        if(!StringUtil.isEmpty(token)){
            return token;
        }*/
        String token = null;

        String url = ConfigUtil.getConfig("niwodai.url");
        String accessCode = ConfigUtil.getConfig("niwodai.merchValidate.accessCode");
        String appId = ConfigUtil.getConfig("niwodai.appId");
        String appKey = ConfigUtil.getConfig("niwodai.appKey");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appId", appId);
        jsonObject.put("appKey", appKey);

        Map<String, String> params = new HashMap<>();
        params.put("accessCode", accessCode);
        params.put("jsonParam", jsonObject.toJSONString());

        try {
            JSONObject returnObj = httpRequest(url, params);
            if (returnObj != null) {
                String success = returnObj.getString("success");
                if ("1".equals(success)) {
                    JSONObject tokenJson = returnObj.getJSONObject("data");
                    token = tokenJson.getString("accessToken");
                    //redisClient.put("nwd_token", token, 60*60*2);
                    logger.info("==NiWoDaiServiceImpl.merchValidate get token:{}", token);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.warn("==NiWoDaiServiceImpl.merchValidate get token: null");
        } finally {
            return token;
        }
    }

    /**
     * 贷款申请
     *
     * @param phone
     * @param realName
     * @param age
     * @param birthTime
     * @param cityName
     * @param amount
     * @return
     */
    @Override
    public Integer loanApplication(String phone, String realName, String age, String birthTime, String cityName, String amount) throws Exception {

//        if(!StringUtil.isEmpty(cityName)){
//            cityName = cityName.replace("市", "");
//            if(!ConfigUtil.getConfig("niwodai.city.allow").contains(cityName)){
//                //如果不支持的城市,就不再调用接口
//                return null;
//            }
//        }
        String url = ConfigUtil.getConfig("niwodai.url");
        String accessCode = ConfigUtil.getConfig("niwodai.loanApplication.accessCode");
        String nwd_ext_aid = ConfigUtil.getConfig("niwodai.nwd_ext_aid");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("time", System.currentTimeMillis());
        jsonObject.put("nwd_ext_aid", nwd_ext_aid);
        //jsonObject.put("sourceId", "");
        jsonObject.put("phone", phone);
        if (!StringUtil.isEmpty(realName)) {
            jsonObject.put("realName", URLEncoder.encode(URLEncoder.encode(realName, "UTF-8"), "UTF-8"));
        }
        if (!StringUtil.isEmpty(age)) {
            jsonObject.put("age", age);
        }
        if (!StringUtil.isEmpty(birthTime)) {
            jsonObject.put("birthTime", birthTime);
        }
        if (!StringUtil.isEmpty(cityName)) {
            jsonObject.put("cityName", URLEncoder.encode(URLEncoder.encode(cityName, "UTF-8"), "UTF-8"));
        }
        if (!StringUtil.isEmpty(amount)) {
            jsonObject.put("amount", amount);
        }
        String token = merchValidate();
        if (!StringUtil.isEmpty(token)) {
            jsonObject.put("token", token);
        } else {
            return 0;
        }


        Map<String, String> params = new HashMap<>();
        params.put("accessCode", accessCode);
        params.put("jsonParam", jsonObject.toJSONString());

        KwThirdback thirdback = new KwThirdback();
        thirdback.setInterfaceCode("niwodai");
        thirdback.setInterfaceName("你我贷");
        thirdback.setMobile(phone);
        thirdback.setSendUrl(url.toString());
        thirdback.setParams(params.toString());
        thirdback.setCode(Constants.BUSINESS_STATUS_FAIL);
        JSONObject returnObj = new JSONObject();
        try {
            returnObj = httpRequest(url, params);
            thirdback.setBackUrl(returnObj.toString());
            thirdback.setHttpCode(200);
            thirdback.setHttpContent(returnObj.toString());

            String success = returnObj.getString("success");
            if ("1".equals(success)) {
                String data = returnObj.getString("data");
                thirdback.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                thirdback.setMessage(data);
                logger.info("==NiWoDaiServiceImpl.loanApplication business success");
            } else {
                String errCode = returnObj.getString("errCode");
                String errMsg = returnObj.getString("errMsg");
                if ("0020".equals(errCode)) {
                    thirdback.setCode(Constants.BUSINESS_STATUS_REPEAT);
                } else {
                    thirdback.setCode(Constants.BUSINESS_STATUS_OTHER);
                }
                thirdback.setMessage(errCode + ":" + errMsg);
                logger.info("==NiWoDaiServiceImpl.loanApplication business success");
            }
        } catch (Exception e) {
            thirdback.setBackUrl(returnObj.toString());
            thirdback.setHttpCode(408);
            thirdback.setHttpContent(returnObj.toString());
            logger.warn("==NiWoDaiServiceImpl.loanApplication business fail");
        } finally {
            kwThirdbackService.insert(thirdback);
            return thirdback.getCode();
        }
    }


    public JSONObject httpRequest(String url, Map<String, String> params) {
        logger.info("==NiWoDaiServiceImpl.httpRequest url:{}, params:{}", url, params);
        HttpUtil.HttpResult hr = HttpUtil.doPostForm(url, params);
        int code = hr.getStatusCode();
        if (code == 200) {
            logger.info("==NiWoDaiServiceImpl.httpRequest http request success. result:{}", hr.toString());
            String content = hr.getContent();
            JSONObject returnMsg = JSONObject.parseObject(content);
            return returnMsg;
        } else {
            logger.warn("==NiWoDaiServiceImpl.httpRequest http requesst fail. code:{}, result:{}", code, hr.toString());
            return null;
        }
    }

    public static void main(String[] args) {
        NiWoDaiServiceImpl niWoDaiService = new NiWoDaiServiceImpl();
        niWoDaiService.merchValidate();
    }
}
